package com.goudan.practice.thread;

/**
 * 多线程交替打印 1~100
 * 经典实现 实现
 */
public class ThreadPrint3 {
    private static int count = 1;

    public static void main(String[] args) {
        Object lock = new Object();

        new Thread(() -> {
            try {
                synchronized (lock) {
                    while (count <= 100) {
                        if (count % 3 == 1) {
                            System.out.println(Thread.currentThread().getName() + "--->" + count);
                            count++;
                        }
                        lock.notifyAll();
                        lock.wait();
                    }
                    lock.notifyAll();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "T1").start();

        new Thread(() -> {
            try {
                synchronized (lock) {
                    while (count <= 100) {
                        if (count % 3 == 2) {
                            System.out.println(Thread.currentThread().getName() + "--->" + count);
                            count++;
                        }
                        lock.notifyAll();
                        lock.wait();
                    }
                    lock.notifyAll();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "T2").start();

        new Thread(() -> {
            try {
                synchronized (lock) {
                    while (count <= 100) {
                        if (count % 3 == 0) {
                            System.out.println(Thread.currentThread().getName() + "--->" + count);
                            count++;
                        }
                        lock.notifyAll();
                        lock.wait();
                    }
                    lock.notifyAll();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "T3").start();

    }

}





